import { User } from "types/user";
import { http } from "utils/http";

// const apiUrl = process.env.REACT_APP_API_URL

/**
 * localStorage 中保存 token 的 key
 */
const localStorageKey = "__auth_provider_token__";

/**
 * 从 localStorage 获取 token
 * @returns
 */
export const getToken = () => window.localStorage.getItem(localStorageKey);

/**
 * 注册/登录 请求返回后提取 user 存入 localStorage
 */
export const handleUserResponse = ({ user }: { user: User }) => {
  window.localStorage.setItem(localStorageKey, user.token || "");
  return user;
};

/**
 * 用户登录
 * @param data
 * @returns
 */
export const login = (data: { username: string; password: string }) => {
  return Promise.resolve(
    http("login", { data, method: "POST" }).then(handleUserResponse)
  );

  // return fetch(`${apiUrl}/login`, {
  //   method: "POST",
  //   headers: {
  //     "Content-Type": "application/json",
  //   },
  //   body: JSON.stringify(data),
  // }).then(async (response) => {
  //   if (response.ok) {
  //     return handleUserResponse(await response.json());
  //   } else {
  //     return Promise.reject(await response.json());
  //   }
  // });
};

/**
 * 用户注册
 * @param data
 * @returns
 */
export const register = (data: { username: string; password: string }) => {
  return Promise.resolve(
    http("register", { data, method: "POST" }).then(handleUserResponse)
  );

  // return fetch(`${apiUrl}/register`, {
  //   method: "POST",
  //   headers: {
  //     "Content-Type": "application/json",
  //   },
  //   body: JSON.stringify(data),
  // }).then(async (response) => {
  //   if (response.ok) {
  //     return handleUserResponse(await response.json());
  //   } else {
  //     return Promise.reject(await response.json());
  //   }
  // });
};

/**
 * 用户登出
 * @returns
 */
export const logout = async () =>
  window.localStorage.removeItem(localStorageKey);
